package com.wnhz.work.yz.fragment.group;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.activity.GoToAddPersonActivity;
import com.wnhz.work.yz.bean.AddPersonTeamBean;
import com.wnhz.work.yz.bean.FinishGroupBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.CircularImage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2017/4/7.
 */
public class AddPersonToGroupFragment extends Fragment {
    private View view;
    private GoToAddPersonActivity activity;
    private ExpandableListView expanded_menu;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        view = inflater.inflate(R.layout.fragment_add_group, container, false);
        activity = (GoToAddPersonActivity) getActivity();
        initView();
        return view;
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }


    @Override
    public void onResume() {
        upLoad();
        super.onResume();
    }

    // 在Android的主线程中运行
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getFinish(FinishGroupBean b) {
        Log.e("13123", "dasdsad");

        Intent intent = new Intent();
        ArrayList<AddPersonTeamBean.InfoEntity.TeamUserEntity> user = new ArrayList<>();
        user.clear();
        boolean flag = false;
        for (int i = 0; i < teams.size(); i++) {
            for (int j = 0; j < teams.get(i).getTeam_user().size(); j++) {
                if (teams.get(i).getTeam_user().get(j).isSelect()) {
                    flag = false;
                    for (int k = 0; k < user.size(); k++) {
                        if (teams.get(i).getTeam_user().get(j).getUser_id().equals(user.get(k).getUser_id())) {
                            flag = true;
                            continue;
                        }
                    }
                    if (!flag)
                        user.add(teams.get(i).getTeam_user().get(j));
                }
            }
        }
//        if (b.getType() == 1) {
//            if (user.size() > 1) {
//                Toast.makeText(activity, "责任人只能有一个", Toast.LENGTH_SHORT).show();
//                return;
//            }
//        }
        intent.putExtra("type", 0);
        intent.putExtra("user", user);
        activity.setResult(Activity.RESULT_OK, intent);
        activity.finish();

    }

    List<AddPersonTeamBean.InfoEntity> teams = new ArrayList<>();

    private void upLoad() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("isTeam", 1);
        activity.showDialog();

        XUtil.Post(Url.GETTEAMLISTBYISTEAM, map, new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        Log.i("----", "onSuccess:= " + result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String res = jsonObject.optString("result");
                            String info = jsonObject.optString("info");
                            if ("1".equals(res)) {
                                Gson gson = new Gson();
                                AddPersonTeamBean bean = gson.fromJson(result, AddPersonTeamBean.class);
                                teams = bean.getInfo();
                            } else {
                                if ("-1".equals(res)) {
                                    info = "请重新登录";
                                }
                                activity.MyToast(info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished() {
                        activity.closeDialog();
                        setData();
                        super.onFinished();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);

                        activity.closeDialog();
                    }
                }

        );
    }


    private void setData() {
        expanded_menu.setAdapter(new BaseExpandableListAdapter() {

            @Override
            public int getGroupCount() {
                return teams.size();
            }

            @Override
            public int getChildrenCount(int groupPosition) {
                int index = 0;
                try {
                    index = teams.get(groupPosition).getTeam_user().size();
                } catch (Exception e) {
                    index = 0;
                }
                return index;
            }

            @Override
            public Object getGroup(int groupPosition) {
                return teams.get(groupPosition);
            }

            @Override
            public Object getChild(int groupPosition, int childPosition) {

                return teams.get(groupPosition).getTeam_user().get(childPosition);
            }

            @Override
            public long getGroupId(int groupPosition) {
                return groupPosition;
            }

            @Override
            public long getChildId(int groupPosition, int childPosition) {
                return childPosition;
            }

            @Override
            public boolean hasStableIds() {
                return false;
            }

            @Override
            public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
                GroupHolder holder;
                if (convertView == null) {
                    holder = new GroupHolder();
                    convertView = View.inflate(activity, R.layout.item_team, null);
                    holder.team_name = (TextView) convertView.findViewById(R.id.team_name);
                    convertView.setTag(holder);
                } else {
                    holder = (GroupHolder) convertView.getTag();
                }
                if (!isExpanded) {
                    Drawable drawable = getResources().getDrawable(R.mipmap.ic_rightarrow);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    holder.team_name.setCompoundDrawables(null, null, drawable, null);
                } else {
                    Drawable drawable = getResources().getDrawable(R.mipmap.nav_bottom_iocn);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    holder.team_name.setCompoundDrawables(null, null, drawable, null);

                }
                holder.team_name.setText(teams.get(groupPosition).getTeam_name() + "(共" + teams.get(groupPosition).getTeam_user().size() + "人)");
                return convertView;
            }

            class GroupHolder {
                TextView team_name;
            }

            @Override
            public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
                ItemHolder holder;
                if (convertView == null) {
                    holder = new ItemHolder();
                    convertView = View.inflate(activity, R.layout.item_person, null);
                    holder.ischoose = (ImageView) convertView.findViewById(R.id.ischoose);
                    holder.head_img = (CircularImage) convertView.findViewById(R.id.head_img);
                    holder.name = (TextView) convertView.findViewById(R.id.name);
                    holder.phone = (TextView) convertView.findViewById(R.id.phone);
                    convertView.setTag(holder);
                } else {
                    holder = (ItemHolder) convertView.getTag();
                }
                x.image().bind(holder.head_img, teams.get(groupPosition).getTeam_user().get(childPosition).getUser_img());
                if (teams.get(groupPosition).getTeam_user().get(childPosition).isSelect()) {
                    holder.ischoose.setImageResource(R.mipmap.ic_choose_li);
                } else {
                    holder.ischoose.setImageResource(R.mipmap.ic_choose_nor);
                }
                holder.name.setText(teams.get(groupPosition).getTeam_user().get(childPosition).getUser_name());
                holder.phone.setText(teams.get(groupPosition).getTeam_user().get(childPosition).getTelephone());
                holder.ischoose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        teams.get(groupPosition).getTeam_user().get(childPosition).setSelect(!teams.get(groupPosition).getTeam_user().get(childPosition).isSelect());
                        notifyDataSetChanged();
                    }
                });
                return convertView;
            }

            class ItemHolder {
                ImageView ischoose;
                CircularImage head_img;
                TextView name, phone;
            }

            @Override
            public boolean isChildSelectable(int groupPosition, int childPosition) {

                return false;
            }
        });
    }

    private void initView() {
        expanded_menu = (ExpandableListView) view.findViewById(R.id.expanded_menu);

    }
}
